package com.partners.controller;

import com.partners.configure.QiniuConfig;
import com.partners.constant.ErrorMessageEnum;
import com.partners.model.ApiResult;
import com.partners.model.BusinessException;
import com.partners.service.UploadFileService;
import com.partners.utils.ApiResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 上传文件到七牛
 * @author liangyongle
 * @date 2018-12-12
 */

@RestController
@RequestMapping("upload")
@Slf4j
public class UploadController {


    @Resource
    private UploadFileService uploadFileService;


    @Resource
    private QiniuConfig qiniuConfig;

    @PostMapping("/uploadFile")
    public ApiResult<Map<String, String>> fileUpload(@RequestParam("photo") MultipartFile file){
        try {
            String path = uploadFileService.uploadFile(file.getBytes());
            Map<String, String> result = new HashMap<>(1);
            result.put("photo", qiniuConfig.getDomain()+"/"+path);
            return ApiResultUtil.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            throw BusinessException.of(ErrorMessageEnum.OPERATION_FAILURE);
        }
    }

    @GetMapping("qrcode")
    public ApiResult createQrCode(){
        String url = "http://baidu.com";
        String qrcode = uploadFileService.createQrcode1(url);
        return ApiResultUtil.ok(qrcode);
    }
}
